package org.friping.mytool.dao;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;

import com.fasterxml.jackson.databind.ObjectMapper;

import org.androidannotations.annotations.AfterInject;
import org.androidannotations.annotations.Bean;
import org.androidannotations.annotations.EBean;
import org.androidannotations.annotations.RootContext;
import org.friping.mytool.helper.FileHelper;

import java.io.IOException;
import java.util.stream.Stream;

@EBean (scope = EBean.Scope.Singleton)
public class DaoHelper {

    private String dbName;
    private final static String SEPARATOR = "--SEPARATOR";
    private ObjectMapper objectMapper = new ObjectMapper();

    @RootContext
    Context context;

    @Bean
    FileHelper fileHelper;

    @AfterInject
    public void init(){
        dbName = context.getPackageName() + ".Mytool" + ".db";

        //FIXME: clean here for now()
        cleanDb();

        String[] dbs = context.databaseList();
        if(dbs != null && dbs.length > 0){
            String existDb = Stream.of(dbs).filter(db -> {
                if(db.equals(dbName)){
                    return true;
                }
                return false;
            }).findFirst().orElse(null);
            if(existDb != null){
                return ;
            }
        }
        String buildSql = null;
        try {
            buildSql = fileHelper.inputStream2String(context.getAssets().open("sql/0_schema.sql"));
        } catch (IOException e) {
            e.printStackTrace();
        }
        try(SQLiteDatabase db = openDb()){
            String[] sqls = buildSql.split(SEPARATOR);
            for(String sql : sqls){
                db.execSQL(sql);
            }
        }
    }

    public void cleanDb(){
        context.deleteDatabase(dbName);
    }

    public SQLiteDatabase openDb(){
        return context.openOrCreateDatabase(dbName, Context.MODE_PRIVATE,null);
    }

}